<script lang="tsx" setup>
import { reactive, ref, watch } from 'vue';
import type { FormRules } from 'naive-ui';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import type { PackageVO, TenantVO } from '@/service/types/tenant';
import { getPackageList } from '@/service/api/tenants/package';
import { addTenant, editTenant, getTenant } from '@/service/api/tenants/tenant';
type Model = Pick<
  TenantVO,
  | 'status'
  | 'companyName'
  | 'licenseNumber'
  | 'address'
  | 'domain'
  | 'intro'
  | 'packageId'
  | 'expireTime'
  | 'remark'
  | 'accountCount'
  | 'contactPhone'
  | 'contactUserName'
>;
const loading = ref(false);
const initLoading = ref(false);
interface Emits {
  (e: 'submitted'): void;
}
const visible = defineModel<boolean>('visible', {
  default: false
});
function closeAddModal() {
  visible.value = false;
}
const current = ref<number | null>(1);
const emit = defineEmits<Emits>();
const packageOptions = ref<PackageVO[]>([]);
defineOptions({
  name: 'ClientForm'
});
const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();
const rules: FormRules = {
  companyName: [
    {
      required: true,
      message: '公司名称不能为空',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 50,
      message: '公司名称不得超过20个字符',
      trigger: 'blur'
    }
  ],
  contactUserName: [
    {
      required: true,
      message: '联系人不能为空',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 20,
      message: '联系人不得超过20个字符',
      trigger: 'blur'
    }
  ],
  contactPhone: [
    {
      required: true,
      message: '联系电话不能为空',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 20,
      message: '联系电话不得超过20个字符',
      trigger: 'blur'
    }
  ],
  packageId: createRequiredRule('请选择套餐'),
  intro: {
    required: false,
    min: 0,
    max: 180,
    message: '企业简介不得超出180个字符',
    trigger: 'blur'
  },
  address: {
    required: false,
    min: 0,
    max: 180,
    message: '企业地址不得超出180个字符',
    trigger: 'blur'
  },
  licenseNumber: {
    required: false,
    min: 0,
    max: 30,
    message: '统一社会信用代码不得超出30个字符',
    trigger: 'blur'
  },
  domain: {
    required: false,
    min: 0,
    max: 200,
    message: '域名不得超出200个字符',
    trigger: 'blur'
  }
};
interface Props {
  currentId?: string | number | null | unknown;
}
const props = defineProps<Props>();

const model: Model = reactive(createDefaultModel());
function createDefaultModel(): Model {
  return {
    status: '0',
    companyName: '',
    licenseNumber: '',
    packageId: null,
    contactPhone: '',
    domain: '',
    intro: '',
    address: '',
    expireTime: null,
    contactUserName: '',
    accountCount: -1
  };
}
const currentModelData = ref<TenantVO>();
const getTenantById = async (id: number) => {
  initLoading.value = true;
  const { error, data } = await getTenant(id);
  if (!error) {
    currentModelData.value = data?.data;
  }
  initLoading.value = false;
};
const handleInitModel = async () => {
  Object.assign(model, createDefaultModel());
  await getTenantById(props.currentId as number);
  Object.assign(model, currentModelData.value);
};

const getPackages = async () => {
  const { error, data } = await getPackageList();
  if (!error) {
    console.log(data);
    // @ts-expect-error 忽略request返回数据的错误
    packageOptions.value = data?.data;
  }
};
const handleReset = async () => {
  current.value = 1;
};
watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    getPackages();
    handleReset();
    restoreValidation();
  }
});

const handleSubmit = async () => {
  loading.value = true;
  const { ...params } = model;
  const { error, data } = await editTenant(params as TenantVO);
  loading.value = false;
  if (!error) {
    (window as any).$message?.success(data?.msg);
    emit('submitted');
    closeAddModal();
  }
};
const shortcuts = reactive({
  永久: 4131619200000
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent title="修改租户" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NSpin :show="initLoading">
          <NFormItem label="公司名称" path="companyName">
            <NInput v-model:value="model.companyName" placeholder="请输入公司名称" />
          </NFormItem>
          <NFormItem label="联系人" path="contactUserName">
            <NInput v-model:value="model.contactUserName" placeholder="请输入联系人" />
          </NFormItem>
          <NFormItem label="联系电话" path="contactPhone">
            <NInput v-model:value="model.contactPhone" placeholder="请输入联系电话" />
          </NFormItem>
          <NFormItem label="社会信用代码" path="licenseNumber">
            <NInput v-model:value="model.licenseNumber" placeholder="请输入统一社会信用代码" />
          </NFormItem>
          <NFormItem label="企业地址" path="address">
            <NInput
              v-model:value="model.address"
              :autosize="{
                minRows: 3,
                maxRows: 5
              }"
              :maxlength="180"
              show-count
              type="textarea"
              placeholder="请输入企业地址"
            />
          </NFormItem>
          <NFormItem label="企业简介" path="intro">
            <NInput
              v-model:value="model.intro"
              :autosize="{
                minRows: 3,
                maxRows: 5
              }"
              :maxlength="180"
              show-count
              type="textarea"
              placeholder="请输入企业简介"
            />
          </NFormItem>
          <NFormItem label="过期时间" path="expireTime">
            <NDatePicker
              v-model:value="model.expireTime"
              :shortcuts="shortcuts"
              class="w-100%"
              clearable
              placeholder="请选择过期时间"
            />
          </NFormItem>
          <NFormItem label="账号数量" path="accountCount">
            <NInputNumber
              v-model:value="model.accountCount"
              class="w-100%"
              clearable
              placeholder="请输入账号最大数量"
            />
            <template #label>
              <FormLabelExtends label="账号数量" tips="-1代表不限制" />
            </template>
          </NFormItem>
          <NFormItem label="绑定域名" path="domain">
            <NInput v-model:value="model.domain" placeholder="请输入绑定域名" />
          </NFormItem>
        </NSpin>
      </NForm>
      <template #footer>
        <NSpace justify="end">
          <NButton @click="closeAddModal">取消</NButton>
          <NButton type="primary" :loading="loading" @click="handleSubmit">提交</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style lang="scss" scoped></style>
